#!/bin/bash
#$1: 0 - 备份走ssh私钥; 1 - 还原ssh私钥
#$2: 密码
#注意事项:


src=${HOME}/.ssh/id_rsa
desc=${HOME}/.backup/priv.bak

oper_flag=$1
passwd=$2

if [ $# -lt 2 ]; then
	echo "[ERROR]: CURLINE[$LINENO], input parameter error"
	exit 1
fi

is_suc()
{
	if [ $? -eq 0 ]; then
		echo "[INFO]: CURLINE[$LINENO], command [$1] is success"
		return 0
	else
		echo ""
		echo "[ERROR]: CURLINE[$LINENO], command [$1] is failed!!!"
		exit 1
	fi
}


file_backup()
{
	local bakpath

	if [[ "$passwd" == "" ]]; then
		echo "[ERROR]: CURLINE[$LINENO], passwd is null"
		exit 1
	fi

	bakpath=`dirname ${desc}`
	is_suc "get backup path"

	if [ ! -d ${bakpath} ]; then
		mkdir -p $bakpath
		is_suc "mkdir -p $bakpath"
	fi

	openssl des3 -salt -k ${passwd} -in ${src} -out ${desc}
	is_suc "openssl des3 -salt -k ${passwd} -in ${src} -out ${desc}"

	rm ${src}
	is_suc "rm ${src}"
}

#$1: 密码
file_restore()
{
	openssl des3 -d -k ${passwd} -salt -in ${desc} -out ${src}
	is_suc "openssl des3 -d -k ${passwd} -salt -in desc -out src"
}

if [[ "${oper_flag}" == "0" ]]; then
	echo "[DEBUG]: CURLINE[$LINENO], start file_backup"
	file_backup passwd
	is_suc "file_backup"
elif [[ "${oper_flag}" == "1" ]]; then
	echo "[DEBUG]: CURLINE[$LINENO], start file_restore"
	file_restore passwd
	is_suc "file_restore"
else
	echo "[ERROR]: CURLINE[$LINENO], input error[${oper_flag}]"
	exit 1
fi


exit 0

